//
//  HomeController.m
//  Custom_Weibo
//
//  Created by LEO on 12/7/15.
//  Copyright © 2015 Leo_Lei. All rights reserved.
//

#import "HomeController.h"
#import "AppDelegate.h"
#import "WeiboModel.h"
#import "HomeTableView.h"
#import "WeiboViewLayoutFrame.h"
#import <AudioToolbox/AudioToolbox.h>

@interface HomeController () {
    HomeTableView *_tableView;
    NSMutableArray *_dataArray;         //  For saving the download data.
    
    ThemeImageView *_updateImageView;   //  The background view of update label.
    ThemeLabel *_updateLabel;           //  Show how many weibo has been refreshed.
}
@end

@implementation HomeController

#pragma mark - SYSTEM_METHODS
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationBar.translucent = NO;
    CGRect tableViewFrame = CGRectMake(0, 0, kScreenWidth,
                                       kScreenHeight - kNavigationBarHeight);
    
    //  Add extra table view to show the data.
    _tableView = [[HomeTableView alloc] initWithFrame:tableViewFrame
                                                style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    
    [self updateNewData];
    /*  Add refresh control to reload data.When use 'self' to execute code in
     block, remember weak the 'self'.
     */
    __weak HomeController *weakSelf = self;
    [_tableView addPullDownRefreshBlock:^{
        [weakSelf updateNewData];
        NSLog(@"Pull down to refresh");
    }];
    
    [_tableView addInfiniteScrollingWithActionHandler:^{
        NSLog(@"Load more");
        [weakSelf reloadOldData];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - GET_OBJECT
- (SinaWeibo *)sinaWeibo {
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    return delegate.sinaWeibo;
}

#pragma mark UPDATE_DATA
- (void)updateNewData {
    //  So as update new data, show the view to notify user.
    [self showHUD:@"Loading..."];
    
    SinaWeibo *weibo = [self sinaWeibo];
    /*  Make a judgement for whether user has given the right to the app, and
     has been admitted to log in.If so, user won't be rewrite the account and
     the password.
     */
    if ([weibo isAuthValid]) {
        NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
        if (_dataArray.count != 0) {
            //  Request for new data.
            WeiboViewLayoutFrame *layoutFrame = _dataArray[0];
            NSString *idStr = layoutFrame.weiboModel.weiboIdStr;
            [params setObject:idStr forKey:@"since_id"];
        }
        
        SinaWeiboRequest *request = [weibo requestWithURL:kHome_Timeline
                                                   params:params
                                               httpMethod:@"GET"
                                                 delegate:self];
        request.tag = kNewDataTag;
    }else {
        [weibo logIn];
    }
}

#pragma mark RELOAD_DATA
- (void)reloadOldData {
    SinaWeibo *weibo = [self sinaWeibo];
    /*  Make a judgement for whether user has given the right to the app, and
     has been admitted to log in.If so, user won't be rewrite the account and
     the password.
     */
    if ([weibo isAuthValid]) {
        NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
        if (_dataArray.count != 0) {
            //  Request for new data.
            WeiboViewLayoutFrame *layoutFrame = [_dataArray lastObject];
            NSString *idStr = layoutFrame.weiboModel.weiboIdStr;
            [params setObject:idStr forKey:@"max_id"];
        }
        
        SinaWeiboRequest *request = [weibo requestWithURL:kHome_Timeline
                                                   params:params
                                               httpMethod:@"GET"
                                                 delegate:self];
        request.tag = kOldDataTag;
    }else {
        [weibo logIn];
    }
}

#pragma mark SHOW_PROMOPT_VIEW
- (void)showNewWeiboCounts:(NSInteger)count {
    //  To make a view to show the weibo has been refreshed.
    if (_updateImageView == nil) {
        //  This image view is made for show the label of refreshing counts.
        CGRect backgroundFrame = CGRectMake(kWeiboSideBlank, - kNavigationBarHeight,
                                            kScreenWidth - kWeiboSideMultiple * kWeiboSideBlank,
                                            kNavigationBarHeight);
        _updateImageView = [[ThemeImageView alloc] initWithFrame:backgroundFrame];
        _updateImageView.imageName = @"timeline_notify";
        [self.view addSubview:_updateImageView];
        
        _updateLabel = [[ThemeLabel alloc] initWithFrame:_updateImageView.bounds];
        _updateLabel.colorName = @"Timeline_Notice_color";
        _updateLabel.backgroundColor = [UIColor clearColor];
        _updateLabel.textAlignment = NSTextAlignmentCenter;
        [_updateImageView addSubview:_updateLabel];
    }
    
    //  To count the refreshed weibo.
    if (count > 0) {
        _updateLabel.text = [NSString stringWithFormat:@"Update %li weibo", count];
        
        //  No matter you have refreshed weibo or not, follow action still does
        [UIView animateWithDuration:0.6 animations:^{
            _updateImageView.transform = CGAffineTransformMakeTranslation(0, kNavigationBarHeight);
        } completion:^(BOOL finished) {
            [UIView animateWithDuration:0.6 animations:^{
                [UIView setAnimationDelay:1];
                _updateImageView.transform = CGAffineTransformIdentity;
            }];
        }];
    }
    
    //  To play the system sound while refreshing
    NSString *soundPath = [[NSBundle mainBundle] pathForResource:kSoundFileNaem
                                                          ofType:nil];
    NSURL *soundUrl = [NSURL fileURLWithPath:soundPath];
    
    SystemSoundID soundId;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)soundUrl, &soundId);
    AudioServicesPlaySystemSound(soundId);
}

#pragma mark - DOWNLOAD_REQUEST
- (void)request:(SinaWeiboRequest *)request didFinishLoadingWithResult:(id)result {
    /*  When request finished, data is already download, stop the indicator,
     switch the loading view into complete view.
     */
    [self didFinishHUD:@"Completed"];
    
    [_tableView.pullToRefreshView stopAnimating];
    [_tableView.infiniteScrollingView stopAnimating];
    
    //  Load the data on the table view.
    NSArray *dicArray = result[@"statuses"];
    NSMutableArray *tempArray = [[NSMutableArray alloc] initWithCapacity:dicArray.count];
    for (NSDictionary *dic in dicArray) {
        WeiboModel *model = [[WeiboModel alloc] initWithDataDic:dic];
        
        //  Rearrange the frame.
        WeiboViewLayoutFrame *layoutFrame = [[WeiboViewLayoutFrame alloc] init];
        layoutFrame.weiboModel = model;
        
        [tempArray addObject:layoutFrame];
    }
    
    if (tempArray.count == 0) {
        return;
    }
    
    //  To make sure whether there is any new weibo downloaded.
    if (_dataArray == nil) {
        _dataArray = tempArray;
    }else {
        if (request.tag == kNewDataTag) {
            //  After we pull to refresh, show how many weibo has been refreshed.
            [self showNewWeiboCounts:tempArray.count];
            
            //  The request is for downloading new data.
            NSRange newRange = NSMakeRange(0, tempArray.count);
            NSIndexSet *indexSet = [[NSIndexSet alloc] initWithIndexesInRange:newRange];
            [_dataArray insertObjects:tempArray atIndexes:indexSet];
        }else if (request.tag == kOldDataTag) {
            //  The request is for reloading old data.
            if (tempArray.count > 1) {
                [tempArray removeObjectAtIndex:0];
                [_dataArray addObjectsFromArray:tempArray];
            }else {
                return;
            }
        }
    }
    _tableView.dataArray = _dataArray;
    [_tableView reloadData];
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
